/*
猫猫模块
上传猫猫图片函数在 upload 函数中实现
*/

package model

import (
    "fmt"

    "gitee.com/keeving/quanta-test-cat/utils/errmsg"
    "github.com/gin-gonic/gin"
    "gorm.io/gorm"
)

type Cat struct {
    gorm.Model
    ID            int      `gorm:"primaryKey" json:"id"`
    Name          string   `gorm:"type:varchar(20)" json:"name"`
    Sex           int      `gorm:"type:varchar(20)" json:"sex"`
    Img           string   `gorm:"type:varchar(200)" json:"img"`
    Color         string   `gorm:"type:varchar(20)" json:"color"`
    Brief         string   `gorm:"type:varchar(20)" json:"brief"`
    Adoption      string   `gorm:"type:varchar(20)" json:"adoption"`
    Sterilization string   `gorm:"type:varchar(20)" json:"sterilization"`
    Guide         string   `gorm:"type:varchar(20)" json:"guide"`
    FishNumber    int      `gorm:"type:int" json:"fishNumber"`
    ImgNumber     int      `gorm:"type:int" json:"imgNumber"`
    Imgs          []string `gorm:"-" json:"imgs"`
}

// 猫猫相册数据库结构
type CatPhoto struct {
    gorm.Model
    CatID int `gorm:"type:int;not null" json:"cat_id"`
    ImgUrl   string `gorm:"type:varchar(200)" json:"img"`
}

// GetCat 获取猫猫信息设置
func GetCat(id int) (Cat, int) {
    var cat Cat
    err = db.Where("ID = ?", id).First(&cat).Error
    if err != nil {
        return cat, errmsg.ERROR
    }
    cat.Imgs, _ = GetCatImgs(cat.ID)
    return cat, errmsg.SUCCESS
}

// CreateCat 创建猫猫信息设置
func CreateCat(data *Cat) int {
    err = db.Create(&data).Error
    if err != nil {
        return errmsg.ERROR
    }
    UploadCatPhoto(data.ID, data.Imgs, 1)
    return errmsg.SUCCESS
}

// 上传到猫猫相册
func UploadCatPhoto(catID int, imgs []string, ImgNum int) (code int) {
    for _, img := range imgs {
        catPhoto := CatPhoto{
            CatID:  catID,
            ImgUrl: img,
        }
        err := db.Create(&catPhoto).Error
        if err != nil {
            return errmsg.ERROR
        }
    }
    db.Model(&Cat{}).Where("ID = ?", catID).UpdateColumn("ImgNumber", gorm.Expr("ImgNumber + ?", ImgNum))
    return errmsg.SUCCESS
}

// UpdateCat 更新猫猫信息设置
func UpdateCat(id int, data *Cat) int {
    var cat Cat
    err = db.Model(&cat).Where("ID = ?", id).Updates(&data).Error
    if err != nil {
        return errmsg.ERROR
    }
    return errmsg.SUCCESS
}

// GetCats 获取猫猫列表
func GetCats(id uint, pageSize int, pageNum int) ([]gin.H, int64) {
    var cats []Cat
    var total int64

    if id != 0 {
        db.Select("id, name, sex, img, color, brief, adoption, sterilization, guide, fishnumber, img, number, imgs").Where(
            "id = ?", id,
        ).Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&cats)
        db.Model(&cats).Where(
            "id = ?", id,
        ).Count(&total)
        return nil, total
    }
    db.Select("id, name, sex, img").Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&cats)
    db.Model(&cats).Count(&total)

    var result []gin.H
    for _, cat := range cats {
        catInfo, _ := GetCat(cat.ID)
        catInfo.Imgs, _ = GetCatImgs(catInfo.ID)
        result = append(result, gin.H{
            "id":       catInfo.ID,
            "name":     catInfo.Name,
            "sex":      catInfo.Sex,
            "img":      catInfo.Img,
            "imgs":     catInfo.Imgs,
        })
    }

    if err != nil {
        return result, 0
    }
    return result, total
}

// 获取猫猫相册
func GetCatImgs(id int) ([]string, int) {
    var imgs []string
    var catPhotos []CatPhoto

    // 从 CatPhoto 表中查询所有与指定 CatID 相关的图片 URL
    err := db.Where("cat_id = ?", id).Order("created_at DESC").Find(&catPhotos).Error
    if err != nil {
        fmt.Println("查询失败:", err)
        return imgs, errmsg.ERROR
    }
    // 将查询结果转换为 []string 类型
    for _, photo := range catPhotos {
        imgs = append(imgs, photo.ImgUrl)
    }
    return imgs, errmsg.SUCCESS
}

// 删除猫猫
func DeleteCat(id int) int {
    var cat Cat
    err = db.Where("id = ?", id).Delete(&cat).Error
    if err != nil {
        return errmsg.ERROR
    }
    err = db.Where("cat_id = ?", id).Delete(&CatPhoto{}).Error
    if err != nil {
        return errmsg.ERROR
    }
    return errmsg.SUCCESS
}

// 模糊搜索猫猫
func SearchCat(name string) ([]*Cat, int, int) {
    var cats []*Cat
    var total int64

    // 使用 LIKE 进行模糊搜索
    tx := db.Where("name LIKE ?", "%"+name+"%").Find(&cats)

    // 获取匹配的结果数量
    if tx.Error != nil {
        return nil, 0, errmsg.ERROR
    }
    tx.Count(&total)

    return cats, int(total), errmsg.SUCCESS
}